import React, { useState, useEffect, useReducer } from 'react'
import Header from '../../components/Header'
import { reqAddShop, reqDetail } from '../../http/api';
import DetailInfo from './DetailInfo/DetailInfo';
import './Detail.less'
import DetailFooter from './DetailFooter/DetailFooter';
// 引入仓库
import { reducer, initState } from '../../pages/Login/user.js'
import { Toast } from 'antd-mobile';
export default function Detail(props) {
    // console.log(props);
    // 1.初始化数据
    const [detaiInfo, setDetaiInfo] = useState({})
    const [state, dispatch] = useReducer(reducer, initState)
    // 2. 一进就发请求
    useEffect(async () => {
        // 3.取出id和type
        let id = props.match.params.id
        // console.log(id);
        let { match: { params: { type } } } = props
        // console.log(type);
        let res = await reqDetail({
            id: id,
            type,
        })
        if (res.data.code === 200) {
            //4. 修改赋值
            setDetaiInfo(res.data.list[0] ? res.data.list[0] : [])
        }

    }, [])

    // 点击加入购物车
    const addShop = () => {
        // console.log(state);
        // console.log(detaiInfo.id);//取出id
        // console.log(detaiInfo);
        let { match: { params: { type } } } = props
        let id = props.match.params.id
        // 发请求
        reqAddShop({
            uid: state.info.uid, type, goodsid: id, num: 1
        }).then(res => {
            if (res.data.code === 200) {
                //1.弹成功
                Toast.success(res.data.msg)
            }
        })
    }
    return (
        <div>
            {/* 头部组件 */}
            <Header title="商品详情" back></Header>
            {/*5.传递给子组件*/}
            <DetailInfo detaiInfo={detaiInfo}></DetailInfo>
            {/* 底部 */}
            <DetailFooter {...props} addShop={() => addShop()}></DetailFooter>
        </div>
    )
}
